package cn.kais.drawer.menu;

import java.util.Objects;

public enum MenuCodeBarSize {

    SIZE_101("101", 101, 50),
    SIZE_202("202", 202, 100),
    SIZE_303("303", 303, 150),
    SIZE_404("404", 404, 200),
    SIZE_505("505", 505, 250),
    ;

    public final String code;
    public final int width;
    public final int height;

    MenuCodeBarSize(String code, int width, int height) {
        this.code = code;
        this.width = width;
        this.height = height;
    }

    public static MenuCodeBarSize onParseCode(String code) {
        int number = doGetNearCode(code);
        for (MenuCodeBarSize menu : MenuCodeBarSize.values()) {
            if (Objects.equals(menu.code, String.valueOf(number))) {
                return menu;
            }
        }
        return SIZE_101;
    }

    /**
     * 获取 条码最接近的尺寸
     */
    private static int doGetNearCode(String code) {
        int number = Integer.parseInt(code);
        int closest = 101;
        for (MenuCodeBarSize menu : MenuCodeBarSize.values()) {
            int diff = Math.abs(menu.width - number);
            if (Math.abs(closest - number) > diff) {
                closest = menu.width;
            }
        }
        return closest;
    }

}
